package com.moyun.controller.resttemplate;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.moyun.model.common.R;
import com.moyun.model.dto.rest.RestDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.util.Map;

/**
 * <h3>moyun-base</h3>
 * <p>RestTemplate控制层</p>
 *
 * @author : ybx
 * @date : 2021-07-09 15:50:51
 **/
@Api(tags = "REST请求接口")
@RestController
@RequestMapping("/rest")
public class RestTemplateController implements Serializable {

    @PostMapping("/get")
    @ApiOperation(value = "调用系统外部(第三方)接口")
    public R getBpm(@RequestBody RestDTO restDto) throws IOException {
        // 将请求头信息封装到 LinkedMultiValueMap 对象中去
        LinkedMultiValueMap headersMap = HashMap2LinkedMultiValueMap(restDto.getHeadersMap());
        // 拼接url参数
        String urlString = getUrlString2(restDto);
        String body = HttpRequest
                .get(urlString)
                .header(headersMap)
//                .charset(CharsetUtil.CHARSET_UTF_8)
                .execute()
                .body();


        JSONObject jsonObject = JSONUtil.parseObj(body);


        return R.ok(jsonObject);
    }

    @PostMapping("/post")
    @ApiOperation(value = "调用bpmpost请求")
    public R postBpm(@RequestBody RestDTO restDto) {
        // 将请求头信息封装到 LinkedMultiValueMap 对象中去
        LinkedMultiValueMap headersMap = HashMap2LinkedMultiValueMap(restDto.getHeadersMap());

        String body = HttpRequest
                .post(restDto.getUrl())
                .header(headersMap)
                .form(restDto.getParamasMap())
                .execute()
                .body();

        JSONObject jsonObject = JSONUtil.parseObj(body);


        return R.ok(jsonObject);
    }

    /**
     * @return void
     * @Author yangboxuan
     * @Description 将hashMap转换成LinkedMultiValueMap
     * @Date 2021/7/13 11:18
     * @Param [restDto]
     **/
    private LinkedMultiValueMap HashMap2LinkedMultiValueMap(Map map) {
        LinkedMultiValueMap<Object, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
        map.forEach((k, v) -> linkedMultiValueMap.add(k, v));
        return linkedMultiValueMap;
    }

    /**
     * @return java.lang.String
     * @Author yangboxuan
     * @Description 拼接参数到url路径中
     * @Date 2021/7/13 11:03
     * @Param [restDto]
     **/
    private String getUrlString(RestDTO restDto) {
        StringBuilder urlBuiler = new StringBuilder(restDto.getUrl());
        urlBuiler.append("?");
        if (!CollectionUtils.isEmpty(restDto.getParamasMap())) {
            for (Map.Entry<String, Object> entry : restDto.getParamasMap().entrySet()) {
                urlBuiler.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }

        return urlBuiler.toString();
    }

    /**
     * @return java.lang.String
     * @Author yangboxuan
     * @Description 拼接参数到url路径中2
     * @Date 2021/7/13 11:03
     * @Param [restDto]
     **/
    private String getUrlString2(RestDTO restDto) {
        String url = restDto.getUrl();
        LinkedMultiValueMap params = HashMap2LinkedMultiValueMap(restDto.getParamasMap());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.queryParams(params).build().toUri();
        return uri.toString();
    }
}
